<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>地址管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
</head>
<body data-user-role="customer">
<!-- 引入增强版全局通知组件 -->
<div th:replace="~{common/enhanced-global-notification :: notification}"></div>

<div th:replace="~{common/customer-navbar :: navbar}"></div>

    <div class="container mt-4">
        <div th:if="${param.success}" class="alert alert-success alert-dismissible fade show">
            操作成功！
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>

        <h2>我的地址</h2>
        <button class="btn btn-primary mb-3" onclick="showAddForm()">添加新地址</button>

        <div id="addressList" th:if="${not #lists.isEmpty(addresses)}">
            <div th:each="address : ${addresses}" class="card mb-3">
                <div class="card-body">
                    <h5 th:text="${address.username}"></h5>
                    <p th:text="${address.address}"></p>
                    <p th:text="${'电话: ' + address.phone}"></p>
                    <p th:text="${'ID: ' + address.addressId }" style="color:red;font-size:12px;"></p>
                    <!-- 删除按钮 -->
                    <button class="btn btn-sm btn-danger delete-btn"
                            th:data-address-id="${address.addressId}">删除</button>
                    <!-- 编辑按钮 (暂时隐藏)
                    <button class="btn btn-sm btn-warning edit-btn"
                            th:data-address-id="${address.addressId}">编辑</button>  -->
                </div>
            </div>
        </div>

        <div th:if="${#lists.isEmpty(addresses)}" class="card">
            <div class="card-body text-center">
                <h5 class="card-title">暂无地址</h5>
                <p class="card-text">点击上方按钮添加您的第一个地址</p>
            </div>
        </div>
    </div>

    <!-- 添加/编辑地址模态框 -->
    <div class="modal fade" id="addressModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">添加地址</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addressForm">
                        <input type="hidden" id="addressId">
                        <div class="mb-3">
                            <label class="form-label">收货人</label>
                            <input type="text" class="form-control" id="username" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">详细地址</label>
                            <textarea class="form-control" id="address" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">联系电话</label>
                            <input type="tel" class="form-control" id="phone" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveAddress()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const modal = new bootstrap.Modal(document.getElementById('addressModal'));
        const userId = /*[[${loggedInUserId}]]*/ '';

        function showAddForm() {
            document.getElementById('modalTitle').textContent = '添加地址';
            document.getElementById('addressForm').reset();
            document.getElementById('addressId').value = '';
            modal.show();
        }

        function showEditForm(addressId) {
            fetch('/address/detail?addressId=' + addressId, {
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => {
                        throw new Error(text || '获取地址详情失败');
                    });
                }
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    throw new Error('无效的响应格式');
                }
                return response.json();
            })
            .then(result => {
                if (!result.success) {
                    throw new Error(result.message || '地址数据获取失败');
                }
                if (!result.data) {
                    // 更友好的处理方式：显示提示并允许重新选择
                    alert('地址不存在或已被删除，请刷新列表后重试');
                    location.reload();
                    return;
                }
                const address = result.data;
                document.getElementById('modalTitle').textContent = '编辑地址';
                document.getElementById('addressId').value = address.addressId;
                document.getElementById('username').value = address.username || '';
                document.getElementById('address').value = address.address || '';
                document.getElementById('phone').value = address.phone || '';
                modal.show();
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取地址详情失败: ' + error.message);
            });
        }

        function generateUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                const r = Math.random() * 16 | 0;
                const v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }

        function saveAddress() {
            const address = {
                addressId: document.getElementById('addressId').value || generateUUID(),
                userId: userId,
                username: document.getElementById('username').value,
                address: document.getElementById('address').value,
                phone: document.getElementById('phone').value
            };

            const url = '/address/add';

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(address)
            })
            .then(response => {
                if (!response.ok) throw new Error('保存请求失败');
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    modal.hide();
                    window.location.href = '/address/list?success=true';
                } else {
                    alert(result.message || '操作失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('保存地址失败: ' + error.message);
            });
        }

        // 使用事件委托绑定按钮点击事件
        document.addEventListener('DOMContentLoaded', function() {
            // 删除按钮事件
            document.addEventListener('click', function(e) {
                if (e.target.classList.contains('delete-btn')) {
                    const addressId = e.target.getAttribute('data-address-id');
                    console.log('删除地址ID:', addressId);
                    if (!addressId) {
                        alert('错误：地址ID为空！');
                        return;
                    }
                    if (confirm('确定要删除这个地址吗？')) {
                        fetch('/address/delete?addressId=' + addressId, {
                            method: 'POST',
                            headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json'
                            }
                        })
                        .then(response => {
                            if (!response.ok) {
                                return response.text().then(text => {
                                    throw new Error(text || '删除请求失败');
                                });
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (data && typeof data === 'object') {
                                if (data.success) {
                                    location.reload();
                                } else {
                                    alert('删除失败: ' + (data.message || '未知错误'));
                                }
                            } else {
                                alert('无效的响应格式');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('删除请求失败: ' + error.message);
                        });
                    }
                }
            });

            // 编辑按钮事件
            document.addEventListener('click', function(e) {
                if (e.target.classList.contains('edit-btn')) {
                    const addressId = e.target.getAttribute('data-address-id');
                    showEditForm(addressId);
                }
            });
        });

        function deleteAddress(addressId) {
            console.log('删除地址ID:', addressId);
            if (!addressId) {
                alert('错误：地址ID为空！');
                return;
            }
            if (confirm('确定要删除这个地址吗？')) {
                fetch('/address/delete?addressId=' + addressId, {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        return response.text().then(text => {
                            throw new Error(text || '删除请求失败');
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data && typeof data === 'object') {
                        if (data.success) {
                            location.reload();
                        } else {
                            alert('删除失败: ' + (data.message || '未知错误'));
                        }
                    } else {
                        alert('无效的响应格式');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除请求失败: ' + error.message);
                });
            }
        }
    </script>
</body>
</html>
